package com.izkml.mlyun.hotreload.websocket;

import cn.hutool.json.JSONUtil;
import com.izkml.mlyun.hotreload.enums.BusinessTypeEnums;
import com.izkml.mlyun.hotreload.enums.ErrorEnums;
import com.izkml.mlyun.hotreload.websocket.handler.DebugWebSocketHandler;
import com.izkml.mlyun.hotreload.websocket.handler.LogWebSocketHandler;
import com.izkml.mlyun.hotreload.websocket.message.ReceiveMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;


@Slf4j
public class WebSocketHandler extends TextWebSocketHandler {

    private DebugWebSocketHandler debugWebSocketHandler;
    private LogWebSocketHandler logWebSocketHandler;

    public WebSocketHandler() {
        debugWebSocketHandler = new DebugWebSocketHandler();
        logWebSocketHandler = new LogWebSocketHandler();
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        logWebSocketHandler.afterConnectionClosed(session, status);
        debugWebSocketHandler.afterConnectionClosed(session, status);
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        logWebSocketHandler.afterConnectionEstablished(session);
        debugWebSocketHandler.afterConnectionEstablished(session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message){
        String commandnd = message.getPayload();
        log.info("WebSocket收到消息：" + commandnd);
        ReceiveMessage receiveMessage = null;
        try {
            receiveMessage = JSONUtil.toBean(commandnd, ReceiveMessage.class);
        } catch (Exception e) {
            log.error(ErrorEnums.PARSE_ERROR.getMessage(), e);
            WebSocketUtil.sendError(session, ErrorEnums.PARSE_ERROR);
            return;
        }

        if(receiveMessage.getBusinessType() == BusinessTypeEnums.DEBUG) {
            debugWebSocketHandler.handleReceiveMessage(session, receiveMessage);
        } else if(receiveMessage.getBusinessType() == BusinessTypeEnums.LOG) {
            logWebSocketHandler.handleReceiveMessage(session, receiveMessage);
        } else {
            if ("ping".equals(receiveMessage.getMethod())) {
                WebSocketUtil.sendSuccess(session);
            }
        }
    }
}
